package com.rachel.materialdemo.adapter;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import com.rachel.materialdemo.common.RBaseViewholder;

/**
 * Created by zhengshaorui on 2017/8/23.
 */

public class HeaderAndFooterAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEAD = 10000;
    private SparseArray<View> mHeaderViews = new SparseArray<>();
    private RecyclerView.Adapter mInnerAdapter;
    public HeaderAndFooterAdapter(RecyclerView.Adapter adapter){
        mInnerAdapter = adapter;
    }


    public void addHeaderView(View view){
        mHeaderViews.put(mHeaderViews.size()+TYPE_HEAD,view);
    }

    public int getHeaderCount(){
        return mHeaderViews.size();
    }

    public boolean isHeaderViewPosition(int position){
        return position < mHeaderViews.size();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderViews.get(viewType) != null){
            RBaseViewholder viewholder = RBaseViewholder.getViewHolder(parent.getContext()
                    ,mHeaderViews.get(viewType));
            return viewholder;
        }
        return mInnerAdapter.onCreateViewHolder(parent,viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (isHeaderViewPosition(position)){
            return;
        }

        mInnerAdapter.onBindViewHolder(holder,position - getHeaderCount());

    }

    @Override
    public int getItemViewType(int position) {
        if (isHeaderViewPosition(position)){
            //return TYPE_HEAD;
            return mHeaderViews.keyAt(position);
        }
        return mInnerAdapter.getItemViewType(position - getHeaderCount());
    }

    /**
     * 获取添加之前的个数
     * @return
     */
    public int getRealItemCount(){
        return mInnerAdapter.getItemCount();
    }

    @Override
    public int getItemCount() {
        return getRealItemCount()+getHeaderCount();
    }
}
